package com.whz.governance.sensitive;

import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.alibaba.csp.sentinel.property.PropertyListener;
import com.alibaba.fastjson.JSON;

import java.util.List;

/**
 * nacos config loader
 *
 * @author whz
 */
public class SensitiveStoreLoader {

    private final SensitiveNacosConfig sensitiveNacosConfig;

    public SensitiveStoreLoader(SensitiveNacosConfig sensitiveNacosConfig) {
        this.sensitiveNacosConfig = sensitiveNacosConfig;
    }

    /**
     * load config form nacos and listen the key change event
     *
     * @param dataId           nacos dataId
     * @param parser           parse nacos config string to T object
     * @param propertyListener listen config key change
     * @param <T>              nacos config type
     */
    public <T> void loadConfigAndListenChanged(String dataId, Converter<String, T> parser, PropertyListener<T> propertyListener) {
        ReadableDataSource<String, T> nacosDataSource = new NacosDataSource<>(
                sensitiveNacosConfig.getServerAddress(),
                sensitiveNacosConfig.getGroupId(),
                dataId,
                parser);

        nacosDataSource.getProperty().addListener(propertyListener);
    }

    /**
     * load sensitive key from nacos and listen it`a changes
     *
     * @param sensitiveEnum    sensitive type
     * @param propertyListener listen key changed
     */
    public void loadConfigAndListenChanged(SensitiveEnum sensitiveEnum, PropertyListener<List<String>> propertyListener) {
        loadConfigAndListenChanged(sensitiveEnum.getDataId(), source -> JSON.parseArray(source, String.class), propertyListener);
    }
}